package com.example.sfzreader.core;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;

import java.lang.reflect.InvocationTargetException;

/**
 * 读取身份证帮助类
 */
public class IDCardReaderClientHelper {
    private boolean isReadFinger = false;//默认不读取身份证指纹
    private IReaderResult iReaderResult;
    private Context context;
    private int deviceType;

    /**
     * 加载上下文
     *
     * @param context Context上下文
     * @return
     */
    public IDCardReaderClientHelper setContext(Context context) {
        this.context = context;
        return this;
    }

    /**
     * 是否读取身份证中的指纹
     *
     * @param isReadFinger true 读取 false不读取
     * @return IDCardReaderClientHelper
     */
    public IDCardReaderClientHelper setReadFinger(boolean isReadFinger) {
        this.isReadFinger = isReadFinger;
        return this;
    }

    /**
     * 读取身份证结果回调接口
     *
     * @param iReaderResult IReaderResult
     * @return IDCardReaderClientHelper
     */
    public IDCardReaderClientHelper setReaderResultCallback(IReaderResult iReaderResult) {
        this.iReaderResult = iReaderResult;
        return this;
    }

    /**
     * 设置读卡器设备的类型
     * @param deviceType 1->usb 2->serial
     * @return
     */
    public IDCardReaderClientHelper setDeviceType(int deviceType) {
        this.deviceType = deviceType;
        return this;
    }

    public IDCardReaderClient builder() {
        if (context == null) {
            context = getApplicationByReflect();
        }
        return new IDCardReaderClient(context, isReadFinger, deviceType, iReaderResult);
    }

    public static Application getApplicationByReflect() {
        try {
            @SuppressLint("PrivateApi")
            Class<?> activityThread = Class.forName("android.app.ActivityThread");
            Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
            Object app = activityThread.getMethod("getApplication").invoke(thread);
            if (app == null) {
                throw new NullPointerException("u should init first");
            }
            return (Application) app;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        throw new NullPointerException("u should init first");
    }
}
